{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
	.layui-form-selected dl{z-index: 1000;}
	.upload-img-block .upload-img-box .upload-default{position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);}
	.multiple-uploading{display: flex;flex-wrap: wrap;}
	.multiple-uploading .multiple-item{position: relative;display: flex;justify-content: center;align-items: center;flex-direction: column;margin-bottom: 10px;padding: 10px;width: 100px;height: 100px;border: 1px dashed #ddd;text-align: center;box-sizing: border-box;line-height: 1;color: #5a5a5a;}
	.multiple-uploading .multiple-item p{line-height: 20px;margin-top: 5px;}
	.multiple-uploading .multiple-item span{display: none;position: absolute;top: -10px;right: -7px;width: 20px;height: 20px;border: 1px solid #999;color: #999;background-color: #fff;border-radius: 50%;line-height: 1;font-size: 18px;cursor: pointer;}
	.multiple-uploading .multiple-item:hover .icon{display: block;}
	.multiple-uploading .multiple-item ~ .multiple-item{margin-left: 10px;}
	.multiple-uploading .iconfont{font-size: 30px;color: #6D7278;}
	#multiple_uploading{cursor: pointer;}
	.multiple-item img{max-width: 100%;max-height: 100%;}

	.form-view .short-label{width:120px}
	.form-view .layui-input-block{margin-left:120px}
	.form-view .word-aux{margin-left:120px}
	.wechat-view{width: 100%;display: flex;}
	.content-view{width: 450px;}
	.form-view{flex:1;}
	.preview-head-div{background:url(STATIC_EXT/diyview/img/preview_head.png) no-repeat 50%/cover;font-size:14px;display:block;height:64px;line-height:82px;text-overflow:ellipsis;white-space:nowrap;overflow:hidden;cursor:pointer;margin:0 auto}
	#title_html{text-align: center;font-size: 16px;font-weight: bold;}

	.content-box::-webkit-scrollbar { width: 0 !important }
	.content-box { -ms-overflow-style: none; }
	.content-box { overflow: -moz-scrollbars-none; }
	.pull-disabled-btn{opacity: .6;filter: alpha(opacity=60);color: #fff;}
</style>
{/block}
{block name="main"}
<div class="wechat-view">
	<div class="content-view" style="    padding: 0px 24px;height: 100%;overflow: auto;">
		<div style="    border: 1px solid rgb(241, 241, 241);width: 375px;">
			<div style="padding: 13px 20px; background: rgb(255, 255, 255); box-shadow: rgb(239, 239, 239) 0px -1px 0px inset;"><div data-v-713f8b68="" class="component-title" style="padding-left: 0px; font-size: 14px; font-weight: bold; color: rgba(0, 0, 0, 0.8);">
				店铺笔记预览
			</div></div>
			<div class="preview-head-div" style="background-color: rgb(255, 255, 255); color: rgb(51, 51, 51); text-align: left;"><span style="text-align: left;"> </span></div>
			<div>
				<h5 id="title_html"></h5>
			</div>
			<div  class="content-box" style="    padding: 9px 12px;box-sizing: border-box;height: 650px;overflow-x: hidden; overflow-y: auto;">
				<div id="content_html"></div>
			</div>
		</div>
	</div>
	<div class="layui-form form-wrap form-view" style="overflow: auto;background: #fff;position: relative;">
		<div class="layui-form-item">
			<label class="layui-form-label short-label">文章链接：</label>
			<div class="layui-input-inline">
				<input type="text" name="note_link"  autocomplete="off" placeholder="请输入文章链接" class="layui-input len-mid">
			</div>
			<div class="layui-input-inline">
				<button class="layui-btn pull-btn" onclick="pullArticle(this)">获取文章</button>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label short-label"><span class="required">*</span>笔记标题：</label>
			<div class="layui-input-inline">
				<input type="text" name="note_title" lay-verify="required" onchange="fetchTitle(this.value)" maxlength="40" autocomplete="off" placeholder="笔记标题最多40个字" class="layui-input len-mid">
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label short-label">摘要：</label>
			<div class="layui-input-block">
				<textarea name="note_abstract" class="layui-textarea len-mid" maxlength="100"></textarea>
			</div>
			<div class="word-aux">笔记摘要最多可输入100个字</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label short-label"><span class="required">*</span>封面：</label>
			<div class="layui-input-inline">
				<input type="radio" name="cover_type" value="0" title="单图" lay-filter="cover_type" checked>
				<input type="radio" name="cover_type" value="1" title="多图" lay-filter="cover_type">
			</div>
		</div>

		<!-- 图片上传 -->
		<div class="layui-form-item">
			<label class="layui-form-label short-label"></label>
			<div class="layui-input-block img-upload">
				<div class="upload-img-block square simple-uploading">
					<div class="upload-img-box" id="img">
						<div class="upload-default">
							<i class="iconfont iconshangchuan"></i>
							<p>点击上传</p>
						</div>
					</div>
					<input type="hidden" name="image" />
					<i class="del">x</i>
				</div>

				<div class="multiple-uploading layui-hide">
					<div class="multiple-item" id="multiple_uploading">
						<i class="iconfont iconshangchuan"></i>
						<p>点击上传</p>
					</div>
				</div>
			</div>
			<div class="word-aux">推荐使用 750x420 像素的图片 最多上传1张</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label short-label"><span class="required">*</span>笔记分组：</label>
			<div class="layui-input-inline">
				<select name="group_id" lay-verify="required">
					<option value="">请选择</option>
					{foreach $group_list as $v}
					<option value="{$v['group_id']}">{$v['group_name']}</option>
					{/foreach}
				</select>
			</div>
		</div>

		<div class="layui-form-item goods_list">
			<label class="layui-form-label short-label">关联商品：</label>
			<div class="layui-input-block">
				<table id="selected_goods_list"></table>
				<button class="layui-btn" onclick="addGoods()">选择商品</button>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label short-label">发布时间：</label>
			<div class="layui-input-inline">
				<input type="radio" name="is_show_release_time" value="1" title="显示" checked>
				<input type="radio" name="is_show_release_time" value="0" title="不显示">
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label short-label">阅读次数：</label>
			<div class="layui-input-inline">
				<input type="radio" name="is_show_read_num" value="1" title="显示" checked>
				<input type="radio" name="is_show_read_num" value="0" title="不显示">
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label short-label">点赞次数：</label>
			<div class="layui-input-inline">
				<input type="radio" name="is_show_dianzan_num" value="1" title="显示" checked>
				<input type="radio" name="is_show_dianzan_num" value="0" title="不显示">
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label short-label">虚拟阅读数：</label>
			<div class="layui-input-inline">
				<input type="number" min="0" name="initial_read_num" onchange="detectionNumType(this,'integral')" class="layui-input">
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label short-label">虚拟点赞数：</label>
			<div class="layui-input-inline">
				<input type="number" min="0" name="initial_dianzan_num" onchange="detectionNumType(this,'integral')" class="layui-input">
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label short-label">排序：</label>
			<div class="layui-input-inline">
				<input type="number" min="0" name="sort" class="layui-input">
			</div>
		</div>

		<div class="form-row">
			<button class="layui-btn" lay-submit lay-filter="save">立即发布</button>
			<button class="layui-btn" lay-submit lay-filter="saveDrafts">保存至草稿箱</button>
			<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
		</div>
		<input type="hidden" name="note_content" value=""/>
		<input type="hidden" name="goods_ids" value="" />
		<input type="hidden" name="note_type" value="{$note_type}" />
	</div>

</div>
<!-- 操作 -->
<script type="text/html" id="operation">
	<div class="table-btn">
		<a class="layui-btn" onclick="delGoods({{d.goods_id}})">删除</a>
	</div>
</script>
{/block}
{block name="script"}
<script>
    //实例化富文本
    var form,repeat_flag,
		IMAGE_MAX = 9, //最多可以上传多少张图片
		imageCollection = [], //图片集合
		selectedGoodsId = [],
		goods_id = [],
		goods_list =[];

    layui.use(['form'], function() {
		form = layui.form;
		repeat_flag = false;

		form.render();

		/**
		 * 图片切换
		 */
		form.on('radio(cover_type)', function(data){
			//0单图  1多图
			if (data.value == 0){

				if(imageCollection.length) {
					imageCollection.splice(1, imageCollection.length);
					var val = '<img src="' + ns.img(imageCollection[0]) + '" alt="">';
					$("#img").html(val);
				}

				$(".simple-uploading").removeClass("layui-hide");
				$(".multiple-uploading").addClass("layui-hide");
				$(".simple-uploading").parents(".layui-form-item").find('.word-aux').text('推荐使用 750x420 像素的图片 最多上传1张');

			} else{
				if(imageCollection.length) {
					var html = '';
					html += `<div class="multiple-item" id="multiple_uploading">`;
					html += `<i class="iconfont iconshangchuan"></i>`;
					html += `<p>点击上传</p>`;
					html += `</div>`;

					for (var i = 0; i < imageCollection.length; i++) {
						html += `<div class="multiple-item">`;
						html += `<img src="${ns.img(imageCollection[i])}" alt="">`;
						html += `<span class="icon">x</span>`;
						html += `</div>`;
					}

					$(".multiple-uploading").html(html);
				}

				$(".simple-uploading").addClass("layui-hide");
				$(".multiple-uploading").removeClass("layui-hide");
				$(".simple-uploading").parents(".layui-form-item").find('.word-aux').text('推荐使用 350x350 像素的图片，最多上传9张');
			}
		});

		/* var upload = new Upload({
			elem: '#img',
			callback:function (res) {
				if (res.code >= 0) {
					imageCollection = [];
					imageCollection.push(res.data.pic_path)
				}
			},
			deleteCallback:function () {
				upload.delete();
				imageCollection = [];
			}
		}); */
		
		// 单图上传
		$("body").on("click", "#img", function () {
		    openAlbum(function (data) {
				imageCollection = [];
				imageCollection.push(data[0].pic_path);
				imageCollection.splice(1, imageCollection.length);
				var val = '<img src="' + ns.img(imageCollection[0]) + '" alt="">';
				$("#img").html(val);
		    }, 1);
		});

		//多图上传
		$("body").on("click","#multiple_uploading", function () {
			var html = '';
			openAlbum(function (data) {
				for (var i = 0; i < data.length; i++) {
					if (imageCollection.length < IMAGE_MAX){
						imageCollection.push(data[i].pic_path);

						html += `<div class="multiple-item">`;
							html += `<img src="${ns.img(data[i].pic_path)}" alt="">`;
							html += `<span class="icon">x</span>`;
						html += `</div>`;
					}
				}
				if (imageCollection.length >= IMAGE_MAX)
					$("#multiple_uploading").addClass("layui-hide");

				$(".multiple-uploading").append(html);

			}, IMAGE_MAX);
		});

		$("body").on('click', '.multiple-item .icon', function () {
			var index = $(this).parent().index() - 1;
			imageCollection.splice(index,1);
			$(this).parent().remove();

			if (imageCollection.length < IMAGE_MAX) $("#multiple_uploading").removeClass("layui-hide");
		});

        /**
         * 表单提交(立即发布)
         */
        form.on('submit(save)', function(data){
            var field = data.field;
            field.status = 1;
            formSubmit(field)
        });

        /**
         * 表单提交(草稿箱)
         */
        form.on('submit(saveDrafts)', function(data){
            var field = data.field;
            field.status = 0;

            formSubmit(field)
        });
    });

    /**
     *  提交
     */
    function formSubmit(data)
    {
		if (!imageCollection.length){
			layer.msg('请选择封面图！', {icon: 5, anim: 6});
			return;
		}

		// if (selectedGoodsId.length == 0) {
		// 	layer.msg('请选择参与活动的商品！', {icon: 5, anim: 6});
		// 	return;
		// }
		if(data.note_content == ''){
			layer.msg('请先获取文章信息！', {icon: 5, anim: 6});
			return;
		}
		data.cover_img = imageCollection.join();

		if(data.sort < 0){
			layer.msg("排序号不能小于0");
			return false;
		}

		if(repeat_flag) return;
		repeat_flag = true;

		$.ajax({
			type: 'POST',
			dataType: 'JSON',
			url: ns.url("notes://shop/notes/add"),
			data: data,
			async: false,
			success: function(res){
				repeat_flag = false;

				if (res.code == 0) {
					layer.confirm('添加成功', {
						title:'操作提示',
						btn: ['返回列表', '继续添加'],
						closeBtn: 0,
						yes: function(){
							if(data.status == 0){
								location.href = ns.url("notes://shop/notes/drafts");
							}else{
								location.href = ns.url("notes://shop/notes/lists");
							}
						},
						btn2: function() {
							location.reload();
						}
					});
				}else{
					layer.msg(res.message);
				}
			}
		})
    }

    // 表格渲染
	renderTable();
    function renderTable(goods_list = []) {
        //展示已知数据
        table = new Table({
            elem: '#selected_goods_list',
            cols: [
                [{
                    field: 'goods_name',
                    title: '商品名称',
                    unresize: 'false',
                    width: '50%'
                }, {
                    field: 'price',
                    title: '商品价格(元)',
                    unresize: 'false',
                    align: 'right',
                    width: '20%',
                    templet: function(data) {
                        return '￥' + data.price;
                    }
                }, {
                    field: 'goods_stock',
                    title: '库存',
                    unresize: 'false',
                    align: 'center',
                    width: '20%'
                }, {
                    title: '操作',
                    toolbar: '#operation',
                    unresize: 'false',
					align:'right'
                }],
            ],
            data: goods_list
        });
    }

	/* 添加商品 */
	function addGoods(){
		goodsSelect(function (res) {
			if (!res.length) return false;
			goods_id = [];
			goods_list = [];
			for(var i=0;i<res.length;i++) {
				goods_id.push(res[i].goods_id);
				goods_list.push(res[i]);
			}

			renderTable(goods_list);
			$("input[name='goods_ids']").val(goods_id.toString());
			selectedGoodsId = goods_id;

		},selectedGoodsId, {mode: "spu"});
	}

    // 删除选中商品
    function delGoods(id) {
        $.each(goods_list, function(index, item) {
            var goods_id = item.goods_id;

            if (id == Number(goods_id)) {
				goods_list.splice(index, 1);
				renderTable(goods_list);
            }
        });

        $.each(selectedGoodsId, function(index, item) {
            if (id == Number(item)) {
				selectedGoodsId.splice(index, 1);
				goods_id = selectedGoodsId;
            }
        });
        $("input[name='goods_ids']").val(goods_id.toString());
    }

    function back() {
        location.href = ns.url("notes://shop/notes/lists");
    }

	//检测数据类型
	function detectionNumType(el, type) {
        var value = $(el).val();
        //大于零 且 不是小数
        if (value < 0 && type == 'integral')
            $(el).val(0);
        else if (type == 'integral')
            $(el).val(Math.round(value));

        //大于1 且 不是小数
        if (value < 1 && type == 'positiveInteger')
            $(el).val(1);
        else if (type == 'positiveInteger')
            $(el).val(Math.round(value));
        //大于零可以是小数
        if (type == 'positiveNumber') {
            value = parseFloat(value).toFixed(2);
            if (value < 0)
                $(el).val(0);
            else
                $(el).val(value);
        }
    }

	/**
	 * 采集公众号文章信息
	 */
    function pullArticle(self_obj){
		if($(self_obj).hasClass('pull-disabled-btn')){
			return;
		}
    	var wechat_url = $('input[name=note_link]').val();
    	if(wechat_url == ''){
			layer.msg('文章链接不可为空!', {icon: 5, anim: 6});
			return false;
		}
		$(self_obj).addClass('pull-disabled-btn');
		$(self_obj).prepend(`<i class="common-loading-layer layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>`);
		$.ajax({
			type: 'POST',
			dataType: 'JSON',
			url: ns.url("notes://shop/notes/pullArticle"),
			data: {wechat_url:$('input[name=note_link]').val()},
			// async: false,
			success: function(res){
				if (res.code >= 0) {
					fetchTitle(res.data.title);
					fetchArticle(res.data.content_html);
					initPullBtn();
				}else{
					layer.msg(res.message);
				}
			}
		})
	}

	function initPullBtn(){
		$(".pull-btn").text('获取文章');
		$(".pull-btn").removeClass('pull-disabled-btn');
	}

	//填充标题
	function fetchTitle(data){
		$('input[name=note_title]').val(data);
		$('#title_html').text(data);
	}
	function fetchArticle(data){
		$('input[name=note_content]').val(data);
		$("#content_html").html(data);
	}
</script>
{/block}